<?php

declare(strict_types=1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Config extends Model
{
    /**
     * 查询 function
     *
     * @param mixed $field     查询字段
     * @param mixed $op        查询表达式
     * @param mixed $condition 查询条件
     * @return array
     */
    public static function select($field, $op = null, $condition = null): array
    {
        $all = Config::where($field, $op, $condition)->select();
        $data = [];
        foreach ($all as $k => $v) {
            $data[$v["key"]] = $v->value;
        }
        return $data;
    }

    /**
     * 保存 function
     *
     * @param array $data
     * @param string $prefix
     * @return boolean
     */
    public static function saves(array $data, string $prefix): bool
    {
        $res = true;
        foreach ($data as $k => $v) {
            $find = Config::where("prefix", $prefix)->where("key", $k)->find();
            if ($find) {
                $update = Config::update(["value" => $v], [["prefix", "=", $prefix], ["key", "=", $k]]);
                if (!$update) {
                    $res = false;
                }
            } else {
                $create = Config::create(["key" => $k, "value" => $v, "prefix" => $prefix]);
                if (!$create) {
                    $res = false;
                }
            }
        }
        return $res;
    }

    /**
     * 更新 function
     *
     * @param array|object $data
     * @param array $where
     * @param array $allowField
     * @param string $suffix
     * @return void
     */
    public static function update(
        array|object $data,
        $where = [],
        array $allowField = [],
        string $suffix = ''
    ) {
        foreach (['create_time', 'update_time', 'delete_time'] as $field) {
            if (isset($data[$field]) && is_string($data[$field])) {
                $data[$field] = strtotime($data[$field]);
            }
        }
        return parent::update($data, $where, $allowField, $suffix);
    }
}
